package com.hrc.springbootdemo.sse;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/sse")
@CrossOrigin
class SseController {

    @GetMapping(path="/")
    public SseEmitter sse() {
        // 延长超时时间到60秒
        SseEmitter sseEmitter = new SseEmitter(60_000L);
        char[] content = "hello world 你好 世界".toCharArray();
        AtomicInteger index = new AtomicInteger(0);
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, r -> new Thread(r, "sse-emitter-thread"));

        executor.scheduleAtFixedRate(() -> {
            int currentIndex = index.getAndIncrement();
            if (currentIndex >= content.length) {
                // 发送完成事件并关闭
                try {
                    sseEmitter.complete();
                } catch (Exception e) {
                    sseEmitter.completeWithError(e);
                }
                executor.shutdown();
                return;
            }

            try {
                sseEmitter.send(SseEmitter.event().data(String.valueOf(content[currentIndex])));
            } catch (IOException e) {
                sseEmitter.completeWithError(e);
                executor.shutdown();
            }
        }, 0, 100, TimeUnit.MILLISECONDS);

        // 添加完成和错误处理回调
        sseEmitter.onCompletion(executor::shutdown);
        sseEmitter.onTimeout(executor::shutdown);
        sseEmitter.onError((e) -> executor.shutdown());

        return sseEmitter;
    }
}